﻿using System;
using System.Windows;
using HappyBa.Core;
using HappyBa.Core.Interfaces;
using Mnk.Library.Common.Log;
using Mnk.Library.Common.MT;
using Mnk.Library.WpfControls;
using Mnk.Library.WpfControls.Dialogs;
using HappyBa.Localization;

namespace HappyBa.Code
{
    class DataCollector : IDataCollector
    {
        private readonly ILog log = LogManager.GetLogger<DataCollector>();
        private readonly IDataCache dataCache;
        private readonly Config config;

        public DataCollector(IDataCache dataCache, Config config)
        {
            this.dataCache = dataCache;
            this.config = config;
        }

        public EventHandler<EventArgs> OnDataChanged { get; set; }

        public void Collect()
        {
            var owner = ((MainWindow)Application.Current.MainWindow);
            DialogsCache.ShowProgress(
                u => Collect(u, owner),
                HappyBaLang.CollectProjectsInformation, 
                Application.Current.MainWindow, 
                false);
        }

        private void Collect(IUpdater updater, Window owner)
        {
            try
            {
                dataCache.Collect(updater);
                Mt.Do(owner, () =>
                {
                    owner.DataContext = null;
                    owner.DataContext = config;
                    OnDataChanged(this, EventArgs.Empty);
                });
            }
            catch (Exception ex)
            {
                log.Write(ex, "Can't collect information");
            }
        }
    }
}
